package com.scnu.hachimi.show;

import com.scnu.hachimi.controller.KeyboardListener;
import com.scnu.hachimi.element.*;
import com.scnu.hachimi.manager.ObjectManager;
import com.scnu.hachimi.manager.ResourcesManager;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;

/**
 * 注入ResourcesManager，ObjectManager
 */

public class GameJPanel extends JPanel implements Runnable {
    private ResourcesManager rm;
    public ObjectManager om;
    private MainJFrame mjf;

    //双缓冲
    private Image offScreenImage = null;

    public double fn = 0, ti;

    public GameJPanel(ResourcesManager rm, ObjectManager om, MainJFrame mjf) {
        this.rm = rm;
        this.om = om;
        this.mjf = mjf;

        om.gjp = this;

//        setIgnoreRepaint(true);  // 禁用Swing自动重绘
//        setDoubleBuffered(true); // 启用双缓冲
//        System.setProperty("sun.java2d.opengl", "true");
        this.setPreferredSize(new Dimension(om.width, om.height + 80));

        //获取焦点
        this.requestFocus();
        this.addKeyListener(new KeyboardListener(om));
    }

    public void quit(int playerNum) throws IOException {
        mjf.showOption(playerNum);
    }

    long tmp = 0;
    double tmp1 = 0;
    String d;
    @Override
    public void paint(Graphics g) {

//        om.updateOnKeyboard();

        if (offScreenImage == null) {
            offScreenImage = this.createImage(this.getWidth(), this.getHeight());
        }
        Graphics gOff = offScreenImage.getGraphics();
        gOff.clearRect(0, 0, this.getWidth(), this.getHeight());

        //黑色背景
        gOff.setColor(Color.BLACK);
        gOff.fillRect(0, 0, this.getWidth(), this.getHeight());

        //分界线
        gOff.setColor(Color.white);
        gOff.drawLine(0, 600, 800, 600);

        // 把全部元素渲染

        gOff.setFont(new Font("微软雅黑", Font.BOLD, 24));
        gOff.drawString("剩余: " + om.enemyCount, 670, 660);

        int p = 1;
        int x = 200;
        for (Player player : om.player) {
            if (player.isAlive) {
                player.paintSelf(gOff, rm);
                gOff.setColor(Color.white);
                gOff.setFont(new Font("微软雅黑", Font.BOLD, 24));
                gOff.drawString("P" + p + ": " + player.hp, x, 660);
                p++;
                x += 100;
            }
        }
        for (Bot bot : om.bot) {
            bot.paintSelf(gOff, rm);
            if (bot.isBOSS) {
                gOff.setColor(Color.white);
                gOff.setFont(new Font("微软雅黑", Font.BOLD, 24));
                gOff.drawString("BOSS: " + bot.hp, 400, 660);
            }
        }


        for (Wall wall : om.wall) {
            wall.paintSelf(gOff, rm);
        }

        for (Base base : om.base) {
            base.paintSelf(gOff, rm);
            //在最下面显示基地血量
            gOff.setColor(Color.white);
            gOff.setFont(new Font("微软雅黑", Font.BOLD, 24));
            gOff.drawString("基地: " + base.hp, 20, 660);
        }

        for (River river : om.river) {
            river.paintSelf(gOff, rm);
        }

        for (Bullet bullet : om.bullet) {
            bullet.paintSelf(gOff, rm);
        }

        for (Boom boom : om.boom) {
            boom.paintSelf(gOff, rm);
        }


        if (om.end) {
            for (String image : om.endImage) {
                gOff.drawImage(rm.imageMap.get(image), 0, 0, null);
            }
            gOff.setFont(new Font("微软雅黑", Font.BOLD, 24));
            gOff.setColor(Color.white);



            if (tmp < om.useTime) {
                if (om.useTime - tmp >= om.useTime/120)
                    tmp += om.useTime/120;
                else tmp = om.useTime;
            }
            if (tmp1 < om.destroyCount) tmp1 += 0.1;


            gOff.drawString(om.mapFilePath + '|' + d, 470, 274);
            gOff.drawString(formatDuration(tmp), 470, 330);
            gOff.drawString(String.valueOf((int)tmp1), 470, 386
            );

        }

        if (om.stop) {
            for (String image : om.stopImage) {
                gOff.drawImage(rm.imageMap.get(image), 0, 0, null);
            }
        }

        g.clearRect(0, 0, this.getWidth(), this.getHeight());
        g.drawImage(offScreenImage, 0, 0, null);
        fn++;

//        System.out.println(fn / ((System.currentTimeMillis() - ti) / 1000));
    }

    Timer timer;

    public void stopGame() {
        timer.stop();
    }

    @Override
    public void run() {
        om.start(); // 启动对象管理器

        ti = System.currentTimeMillis();

        switch (om.diff) {
            case 0:
                d = "简单";
                break;
            case 1:
                d = "普通";
                break;
            case 2:
                d = "困难";
                break;
        }

//        10ms刷新一次
//        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
//
//        executor.scheduleAtFixedRate(this::repaint, 0, 16, java.util.concurrent.TimeUnit.MILLISECONDS);


        timer = new Timer(1, e -> repaint());
        timer.start();

//        while (true) {
//            long t = System.currentTimeMillis();
//            this.repaint();
//            if (System.currentTimeMillis() - t < 10) {
//                try {
//                    Thread.sleep((long) (10 - (System.currentTimeMillis() - t)));
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }

//        while (true) {
//            repaint();
//        }
    }

    public static String formatDuration(long millis) {
        long hours = millis / (60 * 60 * 1000);
        long remaining = millis % (60 * 60 * 1000);

        long minutes = remaining / (60 * 1000);
        remaining %= (60 * 1000);

        long seconds = remaining / 1000;
        long milliseconds = remaining % 1000;

        return String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, milliseconds);
    }

}
